package com.example.jussi.contentresolverdemo;

import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

/**
 * ContentResolver + Cursor 实现手机联系人的查询
 */
public class MainActivity extends AppCompatActivity {
    Button button;
    TextView textView;
    List<String> list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = (TextView) findViewById(R.id.textView2);
        button = (Button) findViewById(R.id.button);
        list = new ArrayList<>();
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                textView.setText("");
                list.clear();
                ContentResolver contentResolver = MainActivity.this.getContentResolver();
                //ContentResolver contentResolver = getContentResolver();
                Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
                while (cursor.moveToNext()) {
                    String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                    int id = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                    StringBuilder builder = new StringBuilder(name + "\n");
                    Cursor cursor2 = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + id, null, null);
                    while (cursor2.moveToNext()){
                        String numberString = cursor2.getString(cursor2.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        builder.append("\t" + numberString + "\n");
                    }
                    list.add(builder.toString());
                }
                for(String str : list){
                    textView.append(str);
                }
            }
        });
    }
}
